package com.vshop.platform.system.crud.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.SecureUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.vshop.framework.core.exception.ServiceException;
import com.vshop.framework.core.util.MapstructUtil;
import com.vshop.framework.mybatisflex.page.PageData;
import com.vshop.framework.mybatisflex.page.PageQuery;
import com.vshop.platform.system.crud.dao.SysClientDao;
import com.vshop.platform.system.domain.entity.SysClient;
import com.vshop.platform.system.domain.param.SysClientParam;
import com.vshop.platform.system.domain.vo.SysClientVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class SysClientService {

    private final SysClientDao sysClientDao;

    /**
     * 分页查询
     */
    public PageData<SysClientVo> page(SysClientParam param, PageQuery pageQuery) {
        QueryWrapper queryWrapper = sysClientDao.buildQueryWrapper(param);
        Page<SysClientVo> page = sysClientDao.pageAs(pageQuery.build(), queryWrapper, SysClientVo.class);
        page.getRecords().forEach(it -> it.setGrantTypeList(List.of(it.getGrantType().split(","))));
        return PageData.build(page);
    }

    /**
     * 保存
     */
    public boolean save(SysClientParam param) {

        if (sysClientDao.checkExistClientKey(param.getClientKey())) {
            throw new ServiceException(param.getClientKey() + " 客户端Key已存在");
        }

        SysClient entity = MapstructUtil.convert(param, SysClient.class);
        entity.setGrantType(String.join(",", param.getGrantTypeList()));
        // 生成 clientId
        String clientKey = param.getClientKey();
        String clientSecret = param.getClientSecret();
        entity.setClientId(SecureUtil.md5(clientKey + clientSecret));
        return sysClientDao.save(entity);
    }

    /**
     * 更新
     */
    public boolean update(SysClientParam param) {
        if (sysClientDao.checkExistClientKey(param.getClientKey())) {
            throw new ServiceException(param.getClientKey() + " 客户端Key已存在");
        }

        SysClient entity = MapstructUtil.convert(param, SysClient.class);
        entity.setGrantType(String.join(",", param.getGrantTypeList()));
        return sysClientDao.updateById(entity);
    }

    /**
     * 删除单条
     */
    public boolean removeById(Long id) {
        return sysClientDao.removeById(id);
    }

    /**
     * 更改状态
     */
    public boolean changeStatus(SysClientParam param) {
        Assert.notNull(param.getId(), "ID不能为空");
        return sysClientDao.changeStatus(param.getId(), param.getStatus());
    }


    public SysClientVo getByClientId(String clientId) {
        SysClient client = sysClientDao.getByClientId(clientId);
        return MapstructUtil.convert(client, SysClientVo.class);
    }

}
